package com.demo.swingquickticket.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.demo.swingquickticket.entity.TicketData;
import com.demo.swingquickticket.entity.TicketDetail;
import com.demo.swingquickticket.swing.layoutUtil.AppLabelCellRenderer;
import com.demo.swingquickticket.swing.model.AppJTableModel;
import com.demo.swingquickticket.swing.view.ticket.TicketPanel;
import com.demo.swingquickticket.util.http.HttpClientUtils;
import com.demo.swingquickticket.util.http.HttpContents;
import com.demo.swingquickticket.util.http.RequestEntity;
import com.demo.swingquickticket.util.http.ResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.swing.*;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TicketPanelService {

    public void search(JTable ticketTable, String date, String from, String to) {

        System.out.println("开始获取" + date + ":" + from + "->" + to + "的车票数据");

        if (StringUtils.isEmpty(from) || StringUtils.isEmpty(to)) {
            System.out.println("获取失败，车站信息错误");
            return;
        }

        from = from.split("\\|")[1];
        to = to.split("\\|")[1];

        List<TicketData> dataList = searchTicket(date, from, to);
        System.out.println("获取成功" + date + ":" + from + "->" + to + "的车票数据，一共" + dataList.size() + "条");
        AppJTableModel tableModel = new AppJTableModel();
        tableModel.setHeader(TicketPanel.TABLE_HEADER);
        tableModel.setColType(TicketPanel.TABLE_TYPE);
        tableModel.setStartDate(date);
        tableModel.setFromStation(from);
        tableModel.setToStation(to);
        List<List<Object>> data = new ArrayList<>();
        dataList.forEach(ticketData -> {
            List<Object> rowData = new ArrayList<>();
            TicketDetail ticketDetail = ticketData.getTicketDetail();
            rowData.add(Boolean.FALSE);
            rowData.add(ticketDetail.getStationTrainCode());
            rowData.add(ticketDetail.getFromStationName());
            rowData.add(ticketDetail.getToStationName());
            rowData.add(ticketDetail.getStartTime());
            rowData.add(ticketDetail.getArriveTime());
            rowData.add(ticketDetail.getLiShi());
            rowData.add(getTicketNum(ticketDetail.getSwzNum(), ticketDetail.getTzNum()));
            rowData.add(getTicketNum(ticketDetail.getZyNum(), null));
            rowData.add(getTicketNum(ticketDetail.getZeNum(), null));
            rowData.add(getTicketNum(ticketDetail.getGrNum(), null));
            rowData.add(getTicketNum(ticketDetail.getRwNum(), null));
            rowData.add(getTicketNum(ticketDetail.getSrrbNum(), null));
            rowData.add(getTicketNum(ticketDetail.getYwNum(), null));
            rowData.add(getTicketNum(ticketDetail.getRzNum(), null));
            rowData.add(getTicketNum(ticketDetail.getYzNum(), null));
            rowData.add(getTicketNum(ticketDetail.getWzNum(), null));
            rowData.add(getTicketNum(ticketDetail.getQtNum(), null));
            data.add(rowData);
        });
        tableModel.setData(data);
        ticketTable.setModel(tableModel);
        setCellRender(ticketTable);
    }



    //根据站台车号获取唯一的车次信息
    public List<TicketData> searchTickets(String date, String from, String to, List<String> stationTrainCodes) {
        List<TicketData> ticketData = this.searchTicket(date, from, to);
        return ticketData.stream().filter(ticket -> stationTrainCodes.contains(ticket.getTicketDetail().getStationTrainCode())).collect(Collectors.toList());
    }


    //获取所有车次信息
    private List<TicketData> searchTicket(String date, String from, String to) {
        List<TicketData> dataList = new ArrayList<>();
        String url = "https://kyfw.12306.cn/otn/leftTicket/query?" +
                "leftTicketDTO.train_date=" + date +
                "&leftTicketDTO.from_station=" + from +
                "&leftTicketDTO.to_station=" + to +
                "&purpose_codes=ADULT";
        RequestEntity requestEntity = new RequestEntity(url, HttpContents.GET_TYPE);
        requestEntity.buildHttpClient();
        ResponseEntity responseEntity = HttpClientUtils.doRequest(requestEntity);
        JSONObject json;
        try {
            json = JSON.parseObject(responseEntity.getResult()).getJSONObject("data");
        } catch (Exception e) {
            log.info("获取票据失败");
            return dataList;
        }
        JSONObject map = json.getJSONObject("map");
        JSONArray result = json.getJSONArray("result");
        for (int i = 0; i < result.size(); i++) {
            String dataStr = result.getString(i);
            String[] data = dataStr.split("\\|");
            TicketData temp = new TicketData();
            TicketDetail ticketDetail = new TicketDetail(data, map);
            temp.setSecretStr(data[0]);
            temp.setButtonTextInfo(data[1]);
            temp.setDate(date);
            temp.setTicketDetail(ticketDetail);
            dataList.add(temp);
        }
        return dataList;
    }


    private String getTicketNum(String num1, String num2) {
        if (StringUtils.isEmpty(num1) && StringUtils.isEmpty(num2)) {
            return "无";
        } else {
            if (StringUtils.isEmpty(num1)) {
                return num2;
            } else {
                return num1;
            }
        }
    }

    private void setCellRender(JTable jTable) {
        TableColumnModel columnModel = jTable.getColumnModel();
        int columnCount = columnModel.getColumnCount();
        for (int i = 0; i < columnCount; i++) {
            TableColumn column = columnModel.getColumn(i);
            if (i == 0) {
                column.setCellRenderer(jTable.getDefaultRenderer(Boolean.class));
                column.setCellEditor(jTable.getDefaultEditor(Boolean.class));
            } else {
                column.setCellRenderer(new AppLabelCellRenderer());
            }

        }
    }

}
